﻿using LSocket.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ClientDemo {
    public partial class ClientForm : Form {
        public ClientForm() {
            InitializeComponent();
            this.Text = "Client";
        }

        private void ClientForm_Load(object sender, EventArgs e) {
            LSocketManager.OnConnected += LSocketManager_OnConnected;
            LSocketManager.OnConnectionClosed += LSocketManager_OnConnectionClosed;
            LSocketManager.OnReceived += LSocketManager_OnReceived;
            LSocketManager.Start();
        }

        private void LSocketManager_OnConnectionClosed() {
            this.Invoke((Action)delegate () {
                MessageBox.Show("与服务器的连接已断开，请重启客户端重试！暂不支持断线重连");
            });
            
        }

        private void LSocketManager_OnConnected() {
            richTextBox1.Text += "连接成功！\r\n";

        }

        private void LSocketManager_OnReceived(byte[] obj) {
            string msg = Encoding.Unicode.GetString(obj, 0, obj.Length);
            richTextBox1.Invoke((Action)delegate () { richTextBox1.Text += msg + "\r\n"; });
        }

        private void richTextBox1_DoubleClick(object sender, EventArgs e) {
            LSocketManager.Send(Encoding.Unicode.GetBytes("Hello LSocket Server"));
        }
    }
}
